<template>
  <div>
    <h1>{{id?'编辑':'新建'}}管理员 </h1>
    <el-form @submit.native.prevent="save" label-width="140px" label-position="right">
      <el-form-item label="用户名" >
        <el-input v-model="model.username" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="密码" >
        <el-input v-model="model.password" placeholder=""></el-input>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      model: {
        username: '',
        password: ''
      }
    }
  },
  props: {
    id: {}
  },
  methods: {
    // 点击按钮提交
    async save () {
      let res
      if (this.id) {
        // 编辑提交
        res = await this.$http.put(`rest/admin_users/${this.id}`, this.model)
      } else {
        // 新增提交
        res = await this.$http.post('rest/admin_users', this.model)
      }
      console.log(res)
      // 注意这里是前端页面路径，不需要加rest
      this.$router.push('/admin_users/list')
      this.$message.success('保存成功')
    },
    // 根据id获取编辑分类的信息
    async fetch () {
      const res = await this.$http.get(`rest/admin_users/${this.id}`)
      this.model = Object.assign({}, this.model, res.data)
      // this.model = res.data
    }
  },
  created () {
    this.id && this.fetch()
  }
}
</script>
